package com.dt.dubai.core.utile;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

@Component
public class I18nUtile {

    @Autowired
    private MessageSource messageSource;

    public String getLocaleFlag(HttpServletRequest request) {
        String LOCALE_SESSION_ATTRIBUTE_NAME = SessionLocaleResolver.class.getName() + ".LOCALE";
        Object locale = request.getSession().getAttribute(LOCALE_SESSION_ATTRIBUTE_NAME);
        return String.valueOf(locale);
    }

    public String getMessage(String code) {
        Locale locale = LocaleContextHolder.getLocale();
        String result = null;
        try {
            result = messageSource.getMessage(code, null, locale);

        } catch (NoSuchMessageException e) {
            //LOGGER.error("Cannot find the error message of internationalization, return the original error message.");
        }
        if (result == null) {
            return code;
        }
        return result;
    }
}

